﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.UI.Core;

namespace Padsurface.App.ViewModels
{
    public partial class PadViewModel
    {
        private CancellationTokenSource _updateRecordingPerformanceTimeCancellation;

        private bool _isRecordingPerformanceToggled;
        public bool IsRecordingPerformanceToggled
        {
            get { return _isRecordingPerformanceToggled; }
            set
            {
                SetProperty(ref _isRecordingPerformanceToggled, value);
                OnRecordingToggled();
            }
        }

        private bool _isRecordingPerformance;
        public bool IsRecordingPerformance
        {
            get { return _isRecordingPerformance; }
            set { SetProperty(ref _isRecordingPerformance, value); }
        }

        private string _recordPerformanceTime;
        public string RecordPerformanceTime
        {
            get { return _recordPerformanceTime; }
            set { SetProperty(ref _recordPerformanceTime, value); }
        }

        private string _recordingPerformanceTime;
        public string RecordingPerformanceTime
        {
            get { return _recordingPerformanceTime; }
            set { SetProperty(ref _recordingPerformanceTime, value); }
        }

        private void OnRecordingToggled()
        {
            lock (_lock)
            {
                if (!IsRecordingPerformance)
                    StartRecording();
                else
                    StopRecording();
            }
        }

        private async void StartRecording()
        {
            IsRecordingPerformance = true;

            _updateRecordingPerformanceTimeCancellation = new CancellationTokenSource();
            UpdateTimer(() => RecordingPerformanceTime = _song.CurrentTime.ToString(@"mm\:ss\.fff"), _updateRecordingPerformanceTimeCancellation.Token);

            await _song.RecordFromStart();

            if (!IsPlaying)
                IsPlayingToggled = true;
        }

        private void StopRecording()
        {
            IsRecordingPerformance = false;
            _updateRecordingPerformanceTimeCancellation.Cancel();

            _song.StopRecording();
        }
    }
}
